package cn.wx.common.persistence.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wx.common.persistence.web.ResponseData;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;


@ControllerAdvice
public class GlobalExceptionHandler {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private MessageSource messageSource;
	
	@ExceptionHandler(value = MyException.class)
    @ResponseBody
    public ResponseData jsonErrorHandler(HttpServletRequest req, MyException e){
		// 获取local
		e.printStackTrace();
		Locale locale = LocaleContextHolder.getLocale();
		// 返回数据封装
		ResponseData resData = new ResponseData();
		resData.setCode(e.getMessage());
		resData.setMsg(messageSource.getMessage(e.getMessage(), null, locale));
		// 打印log日志
		logger.error(messageSource.getMessage(e.getMessage(), null, locale), e);
		return resData;
	}
}
